package com.wnxy.gym.gateway.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.wnxy.gym.common.api.Result;
import com.wnxy.gym.common.api.enums.impl.ResultCode;
import com.wnxy.gym.common.jwt.JwtTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.Duration;


@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private JwtTemplate jwtTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        AntPathMatcher matcher = new AntPathMatcher();

        if (matcher.match("/auth/**", path)) {
            String token = request.getHeaders().getFirst("Authorization");
            token = token.replace("Bearer ", "");
            if (StringUtils.isEmpty(token)) {
                return error(response);
            }
            boolean verifyToken = false;
            try {
                verifyToken = jwtTemplate.verifyToken(token);
            } catch (Exception e) {
                e.printStackTrace();
                return error(response);
            }
            if (!verifyToken) {
                return error(response);
            }
            String telephone = (String) jwtTemplate.parseToken(token, "telephone");

            String redisToken = (String) redisTemplate.opsForValue().get("user:token:" + telephone);
            if (StringUtils.isEmpty(redisToken)) {

                return error(response);
            }
            ServerHttpRequest.Builder mutate = request.mutate();
            mutate.header("telephone", telephone);

            redisTemplate.expire("user:token:" + telephone, Duration.ofMinutes(15l));

        }
        return chain.filter(exchange);
    }

    private Mono<Void> error(ServerHttpResponse response) {
        try {
            Result result = Result.fail(ResultCode.PERMISSION_NO_ACCESS);
            ObjectMapper objectMapper = new ObjectMapper();
            byte[] bytes = objectMapper.writeValueAsBytes(result);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return response.writeWith(Mono.error(e));
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
